#include "menu_form.h"
#include "ui_menu_form.h"
#include "editform.h"
#include <QDebug>

Menu_form::Menu_form(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Menu_form)
{
    ui->setupUi(this);

    this->setWindowFlags(Qt::FramelessWindowHint);

    QStringList sl = QSqlDatabase::drivers();
    QSqlDatabase db= QSqlDatabase::addDatabase("QSQLITE");
    db.setHostName("127.0.0.1");
    db.setDatabaseName("./Smart_menus/db/menu.db");
    bool ret = db.open();
    if(!ret)
    {
        qDebug()<<"open error";
    }

    initTable();

    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);    //每一列间距相等并占满表格宽
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);    //固定模式，不能拖拉改变间距
    ui->tableWidget->setColumnWidth(0,200);    //第几列的宽度
    ui->tableWidget->horizontalHeader()->setStretchLastSection(true);    //最后一行自动拉伸
    //ui->tableWidget->horizontalHeader()->setStyleSheet("QHeaderView::section {background-color:blue;color:white;font-weight:bold;}");    //设置表头样式
    ui->tableWidget->setShowGrid(false);

    on_clearButton_clicked();


}

void Menu_form::initTable()    //给表头添加空行
{
    QSqlQuery query;
    QString sql = "select * from s_menu";
    query.exec(sql);
    while(query.next())
    {
        //获取行数
        int rows = ui->tableWidget->rowCount();
        //添加空行
        ui->tableWidget->insertRow(rows);
        ui->tableWidget->setItem(rows,0, new QTableWidgetItem(query.value(0).toString()));
        ui->tableWidget->setItem(rows,1, new QTableWidgetItem(query.value(1).toString()));
        ui->tableWidget->setItem(rows,2, new QTableWidgetItem(query.value(2).toString()));
        ui->tableWidget->setItem(rows,3, new QTableWidgetItem(query.value(3).toString()));
    }
}

void Menu_form::showData(QString where)    //显示数据
{
    QSqlQuery query;
    QString sql = QString("select * from s_menu %1").arg(where);
    query.exec(sql);
    int editCount = 0;
    int delCount = 0;
    while(query.next())
    {
        //获取行数
        int rows = ui->tableWidget->rowCount();
        //添加空行
        ui->tableWidget->insertRow(rows);
        ui->tableWidget->setItem(rows,0, new QTableWidgetItem(query.value(0).toString()));
        ui->tableWidget->setItem(rows,1, new QTableWidgetItem(query.value(1).toString()));
        ui->tableWidget->setItem(rows,2, new QTableWidgetItem(query.value(2).toString()));
        ui->tableWidget->setItem(rows,3, new QTableWidgetItem(query.value(3).toString()));

        for (int i = 0;i < rows + 1;i++)
           {
               for (int j = 0;j < 4;j++)
               {
                   ui->tableWidget->item(i,j)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
               }
           }

        //给表内添加按钮
        QPushButton *editButton = new QPushButton("编辑");
        editButton->setProperty("editIndex",QVariant(editCount++));    //给该按钮添加属性,属性为所在行数
        QPushButton *delButton = new QPushButton("删除");
        delButton->setProperty("delIndex",QVariant(delCount++));    //给该按钮添加属性,属性为所在行数

        editButton->setFixedSize(QSize(40,20));    //设置样式
        editButton->setStyleSheet("QPushButton{color:white;background-color:rgb(51,204,255);font-family:黑体;border-radius: 10px;}"
                        "QPushButton:pressed{background-color:rgb(51,129,172)}");
        delButton->setFixedSize(QSize(40,20));
        delButton->setStyleSheet("QPushButton{color:white;background-color:rgb(51,204,255);font-family:黑体;border-radius: 10px;}"
                        "QPushButton:pressed{background-color:rgb(51,129,172)}");

        connect(editButton,SIGNAL(clicked()),this,SLOT(editData()));

        connect(delButton,SIGNAL(clicked()),this,SLOT(delData()));

        QHBoxLayout *vLayout = new QHBoxLayout();   //水平布局
        QWidget *widgetButton = new QWidget;    //新建widget
        vLayout->addWidget(editButton);    //添加按钮控件
        vLayout->addSpacing(10);    //添加间隔
        vLayout->addWidget(delButton);    //添加按钮控件
        widgetButton->setLayout(vLayout);    //widget添加布局
        widgetButton->setStyleSheet("QWidget{border:0px}");
        ui->tableWidget->setCellWidget(rows,4,widgetButton);
        ui->tableWidget->setCellWidget(rows,4,widgetButton);
        ui->tableWidget->setCellWidget(rows,4,widgetButton);
        ui->tableWidget->setCellWidget(rows,4,widgetButton);

    }
}

void Menu_form::editData()    //修改菜品
{
    editForm *edit = new editForm;
    edit->setAttribute(Qt::WA_DeleteOnClose);
    edit->show();
    int index = static_cast<QPushButton*>(sender())->property("editIndex").toInt();
    connect(edit,&editForm::editSignal,
            [=]
            (const int &price,const int &usetime,const int &cost)
            {
                QString str = ui->tableWidget->item(index,0)->text();    //获取按钮所在行的菜名

                qDebug()<<"index:"<<index + 1;
                qDebug()<<str<<" "<<price<<" "<<usetime<<" "<<cost;

                QSqlQuery query;
                QString sql = QString("update s_menu set 单价 = %1,出餐时长 = %2,成本 = %3 where 菜名 = '%4'").arg(price).arg(usetime).arg(cost).arg(str);    //构建要执行的mysql语句
                bool ret = query.exec(sql);    //执行mysql语句
                if(!ret)
                {
                    qDebug()<<query.lastError().text();
                }

                ui->tableWidget->setRowCount(0);    //清除表内容不带表头
                ui->tableWidget->clearContents();

                showData(" ");
            });
}

void Menu_form::delData()    //删除菜品
{
    qDebug()<<"index:"<<static_cast<QPushButton*>(sender())->property("delIndex").toInt() + 1;    //显示按钮所在行数

    QString str = ui->tableWidget->item(static_cast<QPushButton*>(sender())->property("delIndex").toInt(),0)->text();    //获取按钮所在行的菜名
    qDebug()<<str;

    QSqlQuery query;
    QString sql = QString("delete from s_menu where 菜名 = '%1'").arg(str);    //构建要执行的mysql语句
    qDebug()<<sql;
    bool ret = query.exec(sql);    //执行mysql语句
    if(!ret)
    {
        qDebug()<<query.lastError().text();
    }

    ui->tableWidget->setRowCount(0);    //清除表内容不带表头
    ui->tableWidget->clearContents();

    showData(" ");
}

void Menu_form::on_add_Button_clicked()    //加菜
{
    /*
    Addmenuvisor w;
    w.start();
    w.function_1();
    */

    inputForm *input = new inputForm;
    input->setAttribute(Qt::WA_DeleteOnClose);
    input->show();

    connect(input,&inputForm::infoSignal,
            [=]
            (const QString &name,const int &price,const int &usetime,const int &cost,const QString &filePath)
            {
                qDebug()<<filePath;

                QSqlQuery query;
                QString sql = QString("insert into s_menu (\"菜名\",\"单价\",\"出餐时长\",\"成本\",\"图片\") values ('%1',%2,%3,%4,'%5')")
                        .arg(name).arg(price).arg(usetime).arg(cost).arg(filePath);

                bool ret = query.exec(sql);
                if(!ret)
                {
                    qDebug()<<query.lastError().text();
                }

                ui->tableWidget->setRowCount(0);
                showData("");
            });
}

void Menu_form::on_clearButton_clicked()    //刷新
{
    ui->tableWidget->setRowCount(0);
    QString where = "";
    showData(where);
}

Menu_form::~Menu_form()
{
    delete ui;
}

void Menu_form::on_pushButton_clicked()
{
    QString text = QString("where 菜名 = '%1'").arg(ui->lineEdit->text());
    qDebug()<<text;
    ui->tableWidget->setRowCount(0);
    showData(text);

}
